#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QFileDialog"
#include "QMessageBox"
#include <QDate>
#include <QDate>
#include "QDebug"
#include "QTextCodec"
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    bootpath = QCoreApplication::applicationDirPath() + "/bootfile";
    QDir directory(bootpath);

    if (directory.exists()) {
        QStringList files = directory.entryList(QDir::Files); // 获取目录中的文件
        ui->comboBox->addItems(files);
    }

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setdefaultpath(void)
{


    if(args.length()>0)
    {
          QFileInfo  fileinfo =QFileInfo(args.at(0));
          apppath = args.at(0).split('.').at(0);
          ui->lineEditapp->setText(apppath + ".hex");
          outname =  fileinfo.baseName() + "(boot).hex";
          outnamenoboot =  fileinfo.baseName() + ".hex";
    }
    if(args.length()>1)
    {
      outpath = args.at(1);
      ui->lineEditappoutput->setText(outname);
    }
    if(args.length()>2)
    {
      bootpath =  outpath = args.at(2);
    }
}


void MainWindow::on_pushButton_2_clicked()
{
    QFileDialog *dlg = new QFileDialog();
    QString filepath = dlg->getOpenFileName(this,"打开文件","/","file(*.hex)");
    ui->lineEditapp->setText(filepath);
}

bool MainWindow:: ReadHexLineData(HexFormatForLine* out,const QByteArray & ba)
{
     unsigned char i,checkoutCal=0;

    //计算校验值
     for(i=0;i < ba.size()-1;i++){
        checkoutCal += (unsigned char)ba.at(i);
     }
     checkoutCal = 0x100-checkoutCal;
     //获取个部分域的值
     out->datalen =(unsigned char)ba.at(0);
     out->addr = ((unsigned char)ba.at(1)<<8)|(unsigned char)ba.at(2);
     out->datatype = (unsigned char)ba.at(3);
     memset(out->databuf,0,sizeof(out->databuf));
     for(i = 0;i<out->datalen;i++){
        out->databuf[i] = (unsigned char)ba.at(4+i);
     }
     out->checkout = (unsigned char)ba.at(4+i);

    //比较读取的校验值和计算的校验值是否一致
    if(checkoutCal == out->checkout){
        return true;
    }
    return false;
}

QString MainWindow::setdate(QString path)
{
    QString datestr;
    QString timestr;
   if(ui->checkBoxdate->isChecked())
   {
     QStringList paths = path.split('.');
     QDate date = QDate::currentDate();
     QTime time = QTime::currentTime();
     datestr = date.toString("yyyyMMdd");
     timestr =time.toString("hhmm");
     return  paths.at(0) + datestr + timestr +"." + paths.at(1);
   }
   else
      return  path;
}
void MainWindow::on_pushButtonoutfile_clicked()
{
    QFileDialog *dlg = new QFileDialog();
    HexFormatForLine HexDataStr;
    QString name = outpath + "/" + outname;
    QString bootfilepath = bootpath + "/" + ui->comboBox->currentText();
    bool ret;

    QString filepath = dlg->getSaveFileName(this,"打开文件",name,"file(*.hex)");
    if(filepath.isEmpty())
    {
        return;
    }
    filepath = setdate(filepath);
    QFile *mergeoutfile = new QFile(filepath);
    if(!mergeoutfile->open(QIODevice::WriteOnly))
    {
        ui->label_info->setText("创建合并失败");
        return ;
    }
    ui->lineEditappoutput->setText(filepath);

    QByteArray  outfile;
    /*读BOOT*/
    QFile bootfile(bootfilepath);
    if(!bootfile.open(QIODevice::ReadOnly))
    {
       ui->label_info->setText("打开BOOTFile失败");
       return ;
    }
    QByteArray alinedatahex;
    QByteArray alinedata;
    while(!bootfile.atEnd())
    {
        alinedata = bootfile.readLine();
        alinedatahex = QByteArray::fromHex(alinedata);//从hex文件中读取一行
        ret = ReadHexLineData(&HexDataStr,alinedatahex);//将一行数据解读到HexDataStr结构体
        if(!ret){
           ui->label_info->setText("Boot File 解析失败");
           bootfile.close();//关闭输入文件
           return;

        }
        if(HexDataStr.datatype==0x01)//结束标志
        {
            break;
        }
        else if (HexDataStr.datatype == 0x05)//入口地址
        {
            outfile.append(alinedata);
        }
        else//数据等
        {
          outfile.append(alinedata);
        }
     }
     bootfile.close();

     /*读APP*/
     QFile APPfile(ui->lineEditapp->text());
     if(!APPfile.open(QIODevice::ReadOnly))
     {
        ui->label_info->setText("打开app 失败");
        return ;
     }


     while(!APPfile.atEnd())
     {
         outfile.append ( APPfile.readLine());
     }
     APPfile.close();

     mergeoutfile->write(outfile);
     mergeoutfile->close();
     delete  mergeoutfile;

     QFileInfo  mergeoutfileinfo =QFileInfo(filepath);
     QString readme = mergeoutfileinfo.path() + "/Readme.txt";
     QTextCodec * qc = QTextCodec::codecForName("utf-8");
     QFile  readmefile(readme);

     if(readmefile.exists())
     {
         if(readmefile.open(QIODevice::Append))
         {
                QTextStream  stream(&readmefile);
                 stream.setCodec("utf-8") ;
                 stream << '\n' <<'\n';
                 stream << mergeoutfileinfo.fileName();
                 stream << '\n';
                 stream << ui->textEdit->toPlainText();
         }
     }
     else
     {
         if(readmefile.open(QIODevice::ReadWrite))
         {
              QTextStream  stream(&readmefile);
              stream.setCodec("utf-8") ;
              stream << mergeoutfileinfo.fileName();
              stream << '\n';
              stream << ui->textEdit->toPlainText();
         }
      }
     readmefile.close();
     ui->label_info->setText("创建完成");
}

void MainWindow::on_pushButton_only_clicked()
{
    QFileDialog *dlg = new QFileDialog();
    QString name = outpath + "/" + outnamenoboot;
    QString filepath = dlg->getSaveFileName(this,"打开文件",name,"file(*.hex)");
    ui->lineEditappoutput->setText(filepath);
    if(filepath.isEmpty())
    {
        return;
    }
    filepath = setdate(filepath);
    if(QFile::exists(filepath))
    {
         QFile::remove(filepath);
    }
    //开始复制
    QFile::copy(ui->lineEditapp->text(),filepath);


    QFileInfo  mergeoutfileinfo =QFileInfo(filepath);
    QString readme = mergeoutfileinfo.path() + "/Readme.txt";
    QFile  readmefile(readme);
    if(readmefile.exists())
    {
        if(readmefile.open(QIODevice::Append))
        {
               QTextStream  stream(&readmefile);
                stream.setCodec("utf-8") ;
                stream << '\n' <<'\n';
                stream << mergeoutfileinfo.fileName();
                stream << '\n';
                stream << ui->textEdit->toPlainText();
        }
    }
    else
    {
        if(readmefile.open(QIODevice::ReadWrite))
        {
             QTextStream  stream(&readmefile);
             stream.setCodec("utf-8") ;
             stream << mergeoutfileinfo.fileName();
             stream << '\n';
             stream << ui->textEdit->toPlainText();
        }
     }
    readmefile.close();
    ui->label_info->setText("创建完成");
}

